package com.example.rpcdemo.client.config;

import com.example.rpcdemo.core.client.RpcClient;
import com.example.rpcdemo.core.client.RpcProxy;
import com.example.rpcdemo.api.HelloService;
import com.example.rpcdemo.registry.ServiceRegistry;
import com.example.rpcdemo.registry.ServiceInstance;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RpcClientConfig {
    
    @Value("${rpc.server.host:localhost}")
    private String serverHost;
    
    @Value("${rpc.server.port:8080}")
    private int serverPort;
    
    @Bean
    public RpcClient rpcClient() {
        // 使用服务发现获取真实的服务地址
        try {
            ServiceInstance instance = ServiceRegistry.getInstance()
                .discoverByInterface("com.example.rpcdemo.api.HelloService");

            if (instance == null || instance.getHost() == null || instance.getHost().trim().isEmpty()) {
                throw new RuntimeException("Invalid service instance");
            }

            return new RpcClient(instance.getHost(), instance.getPort());
        } catch (Exception e) {
            // 服务发现失败，使用默认配置
            System.out.println("Service discovery failed, using default config: " + serverHost + ":" + serverPort);
            return new RpcClient(serverHost, serverPort);
        }
    }
    
    @Bean
    public RpcProxy rpcProxy(RpcClient rpcClient) {
        return new RpcProxy(rpcClient);
    }
    
    @Bean
    public HelloService helloService(RpcProxy rpcProxy) {
        return rpcProxy.create(HelloService.class, "helloService");
    }
}